<template>
    <div class="wrapper">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片 -->
        <el-card>
            <!-- 注意区域 -->
             <el-alert
                title="注意：只允许为第三级设置相关参数！"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>

            <!-- 商品分类信息级联选择器 -->
            <el-row>
                <span class="fontSetup">请选择商品分类：</span>
                <el-cascader
                    v-model="cascaderValue"
                    :options="commodity_categories_info"
                    :props="selectProp"
                    @change="handlerChange">
                </el-cascader>
            </el-row>

            <!-- tab标签页 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <!-- 动态参数 -->
                <el-tab-pane label="动态参数" name="active">
                    <el-button :disabled='is_btn_disable' size="small" type="primary" @click="add_active_params">添加参数</el-button>
                    <!-- 动态属性表格表格 -->
                    <el-table
                        :data="active_data"
                        style="width: 100%"
                        border>
                        <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-tag
                                v-for="(tag, i) in props.row.attr_vals"
                                :key="i"
                                closable
                                @close='handlerClose(props.row, i)'>
                                {{tag}}
                            </el-tag>
                            <!-- new tag -->
                            <el-input
                                class="input-new-tag"
                                v-if="inputVisible"
                                v-model="inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm((props.row))"
                                @blur="handleInputConfirm((props.row))"
                            >
                            </el-input>
                            <el-button 
                                v-else class="button-new-tag" 
                                size="small" 
                                @click="showInput"
                            >+ New Tag</el-button>
                        </template>
                        </el-table-column>
                        <el-table-column
                            label="序号"
                            type="index"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            label="参数名称"
                            prop="attr_name">
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template v-slot="scope">
                                <el-button size="small" 
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="edit_params(scope.row)"
                                >编辑</el-button>
                                <el-button size="small" 
                                    icon="el-icon-delete"
                                    type="danger"
                                    @click="delete_params(scope.row)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!-- 静态参数 -->
                <el-tab-pane label="静态属性" name="second">
                    <el-button :disabled='is_btn_disable'  size="small" type="primary"  @click="add_active_params">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table
                        :data="static_data"
                        style="width: 100%"
                        border>
                        <el-table-column type="expand">
                            <template slot-scope="props">
                                <el-tag
                                    v-for="(tag, i) in props.row.attr_vals"
                                    :key="i"
                                    closable
                                    @close='handlerClose(props.row, i)'>
                                    {{tag}}
                                </el-tag>

                                <!-- new tag -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="inputVisible"
                                    v-model="inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm((props.row))"
                                    @blur="handleInputConfirm((props.row))"
                                >
                                </el-input>
                                <el-button 
                                    v-else class="button-new-tag" 
                                    size="small" 
                                    @click="showInput"
                                >+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="序号"
                            type="index"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            label="属性名称"
                            prop="attr_name">
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template v-slot="scope">
                                <el-button size="small" 
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="edit_params(scope.row)"
                                >编辑</el-button>
                                <el-button size="small" 
                                    icon="el-icon-delete"
                                    type="danger"
                                    @click="delete_params(scope.row)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <!-- 添加动态参数 -->
            <el-dialog
                :title="'添加' + btn_text"
                :visible.sync="add_active_params_value.dialog"
                width="30%">
                <el-form :model="add_active_params_value" :rules="add_active_params_value.rules" ref="ruleForm" label-width="80px">
                     <el-form-item label="参数名称" prop="value">
                        <el-input v-model="add_active_params_value.value"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="reset_add_params()">取 消</el-button>
                    <el-button type="primary" @click="add_active_check()">添加</el-button>
                </span>
            </el-dialog>

            <!-- 编辑参数 -->
            <el-dialog
                :title="'编辑' + btn_text"
                :visible.sync="edit_active_params_value.dialog"
                width="30%">
                <el-form :model="edit_active_params_value" :rules="edit_active_params_value.rules" ref="edit_ruleForm" label-width="80px">
                     <el-form-item label="参数名称" prop="value">
                        <el-input v-model="edit_active_params_value.value" ref="edit_input"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="reset_edit_params()">取 消</el-button>
                    <el-button type="primary" @click="edit_active_check()">添加</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: "Params",
        data() {
            return {
                // 商品分类列表
                commodity_categories_info: [],
                // 选择的商品列表值
                cascaderValue: [],
                // 级联选择器prop配置
                selectProp: { 
                    expandTrigger: 'hover', 
                    value: 'cat_id', 
                    label: 'cat_name', 
                    children: 'children'
                },
                // 默认选中动态参数
                activeName: 'active',
                // 参数类型 [only,many]
                parasmType: 'many',
                // 动态参数
                active_data: [],
                // 静态参数
                static_data: [],
                // 添加参数
                add_active_params_value: {
                    dialog: false,
                    value: '',
                    rules: {
                        value: [{ required: true, message: '请输入参数名称', trigger: 'blur' },]
                    }
                },
                // 编辑参数
                edit_active_params_value: {
                    dialog: false,
                    value: '',
                    rules: {
                        value: [{ required: true, message: '请输入参数名称', trigger: 'blur' },]
                    },
                    cat_id: '',
                    attr_id: '',
                },

                // 新建tag input对话框
                inputVisible: false,
                inputValue: ''
            }
        },
        created() {
            this.get_commodity_categories_data();
        },
        methods: {
            // 获取所有商品分类列表
            async get_commodity_categories_data() {
                let {data:res} = await this.$http.get('/categories');
                if(res.meta.status != 200) return this.$message.error('获取商品分类列表失败');
                this.commodity_categories_info = res.data;
            },
            // 级联选择框中选项发生变化，会触发这个函数
            async handlerChange() {
                if(this.cascaderValue.length !== 3) {
                    this.cascaderValue = [];
                    return
                }
                let {data: res} = await this.$http.get(`categories/${this.cascaderValue[2]}/attributes`, {
                    params: {
                        sel: this.parasmType
                    }
                })
                if(res.meta.status !== 200) return this.$message.error('获取参数列表失败');
                // 判断是动态数据还是静态数据并分别保存
                if(this.parasmType === 'many') {
                    res.data.forEach((item, i) => {
                        if(item.attr_vals === '') return item.attr_vals = []
                        res.data[i].attr_vals = item.attr_vals.split(',');
                    })
                    this.active_data = res.data;
                }else {
                    res.data.forEach((item, i) => {
                        if(item.attr_vals === '') return item.attr_vals = []
                        res.data[i].attr_vals = item.attr_vals.split(',');
                    })
                    this.static_data = res.data;
                }
            },
            // tab标签页发生变化时触发这个函数
            handleClick(tab) {
                this.parasmType = tab._uid === 30 ? 'many' : 'only';
                this.handlerChange();
            },
            // 添加动态参数
            add_active_params() {
                this.add_active_params_value.dialog = true;
            },
            // 添加参数确认
            add_active_check() {
                this.$refs.ruleForm.validate(async valid => {
                    if(!valid) return this.$message.error('请输入参数名称');
                    let {data: res} = await this.$http.post(`categories/${this.cascaderValue[2]}/attributes`, {
                        attr_name: this.add_active_params_value.value,
                        attr_sel: this.parasmType,
                    })
                    if(res.meta.status !== 201) return this.$message.error('添加参数失败');
                    this.$message.success('添加参数成功');
                    this.handlerChange();
                    this.reset_add_params();
                    this.add_active_params_value.dialog = false;
                })
            },
            // 重置添加参数输入框
            reset_add_params() {
                this.add_active_params_value.dialog = false;
            },
            // 删除参数
            delete_params({cat_id, attr_id}) {
                this.$messageBox.confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        const {data: res} = await this.$http.delete(`categories/${cat_id}/attributes/${attr_id}`);
                        if(res.meta.status !== 200) this.$message.error('删除参数失败');
                        this.$message.success('删除参数成功')
                        this.handlerChange();
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });   
                });       
                
            },
            // 编辑参数
            edit_params({cat_id, attr_id, attr_name}) {
                this.edit_active_params_value.dialog = true;
                this.edit_active_params_value.value = attr_name;
                this.edit_active_params_value.cat_id = cat_id
                this.edit_active_params_value.attr_id = attr_id;
                this.$nextTick(() => {
                    this.$refs.edit_input.focus();
                })
            },
            // 编辑对话框确认函数
            edit_active_check() {
                this.$refs.edit_ruleForm.validate(async valid => {
                    if(!valid) return
                    const {data: res} = await this.$http.put(`categories/${this.edit_active_params_value.cat_id}/attributes/${this.edit_active_params_value.attr_id}`, {
                        attr_name: this.edit_active_params_value.value,
                        attr_sel: this.parasmType
                    })
                    if(res.meta.status !== 200) return this.$message.error('修改参数失败')
                    this.handlerChange();
                    this.$message.success('参数更新成功')
                    this.edit_active_params_value.dialog = false;
                })
            },
            // 重置编辑表单
            reset_edit_params() {
                this.edit_active_params_value.dialog = false;
                this.$refs.edit_ruleForm.resetFields()
            },
            
            // 激活input
            showInput() {
                this.inputVisible = true;
                this.$nextTick(() => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            async put_params(row) {
                const {data: res} = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join()
                })
                if(res.meta.status !== 200) return this.$message.error('更新参数失败')
            },
            // add new tag
            handleInputConfirm(row) {
                if(this.inputValue.trim()) {
                    row.attr_vals.push(this.inputValue);
                    this.put_params(row);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            // 删除标签
            handlerClose(row, i) {
                row.attr_vals.splice(i, 1);
                this.put_params(row);
            }
            
            
        },
        computed: {
            // 是否禁用添加参数或添加属性
            is_btn_disable() {
                if(this.cascaderValue.length !== 3) {
                    return true
                }else {
                    return false
                }
            },
            // 计算Text
            btn_text() {
                return this.parasmType === 'many' ? "动态参数" : '静态属性'
            }
        }
    };
</script>

<style lang='less' scoped>
    .wrapper{
        width: 100%;
        height: 0px;
        padding: 10px 20px;
        box-sizing: border-box;
        .el-tag{
            margin: 10px;
        }
        .el-alert{
            margin-bottom: 15px;
        }
        .fontSetup{
            font-size: 14px;
            font-family: 宋体;
            color: coral;
            font-weight: 700;
        }
        .el-tag + .el-tag {
            margin-left: 10px;
        }
        .button-new-tag {
            margin: 10px;
            height: 32px;
            line-height: 30px;
            padding-top: 0;
            padding-bottom: 0;
        }
        .input-new-tag {
            width: 200px;
            margin: 10px;
            vertical-align: bottom;
        }
    }
</style>